<?php

namespace app\data\model;

use app\index\exception\LogicException;
use think\admin\Model;

class ActUserModel extends Model
{
    protected $table = 'act_user';
    const STATUS_FORBID = 2;
    const DEFAULT_PROFILE = '/public/activity/images/user3.png';

    /*************************** 获取器 ***************************/

    public function getNameAttr($value)
    {
        return $value ?: '未命名';
    }

    public function getProfileAttr($value)
    {
        return $value ?: self::DEFAULT_PROFILE;
    }

    /*************************** 接口 ***************************/


    public function getRolesAttr($value){
        return $value !='' ? explode(',',$value) : [];
    }
    /**
     * 创建用户
     * @param $user
     * @return ActUserModel|\think\Model
     */
    public static function createUser($user)
    {
        $email_exist = self::where('email', @$user['email'])->value('id');
        if ($email_exist) {
            throw new LogicException('邮箱已存在!');
        }

        $phone_exist = self::where('phone', @$user['phone'])->value('id');
        if ($phone_exist) {
            throw new LogicException('手机号已存在!');
        }

        $user['password'] = password_hash($user['password'], PASSWORD_DEFAULT);

        return self::create($user);
    }

    public function checkPassword($passwrod)
    {
        return password_verify($passwrod, $this->password);
    }

    public function changePassword($old_password, $new_password)
    {
        if (!$this->checkPassword($old_password)) {
            throw new LogicException('旧密码错误');
        }
        $this->password = password_hash($new_password, PASSWORD_DEFAULT);
        return $this->save();

    }

    public function ifForbid()
    {
        return $this->status === self::STATUS_FORBID;

    }

}